package com.base.vistter.iframe.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson2.JSON;
import com.base.vistter.iframe.bean.Result;
import com.base.vistter.iframe.exception.IframeException;
import com.base.vistter.iframe.menu.ErrorLoginEnum;
import com.base.vistter.iframe.template.MinioTemplate;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@Component
public class IoUtils {

    public static final String SYMBOL_PLUS = "+";

    public static final String ENCODER_SYMBOL_PLUS = "%20";

    private static MinioTemplate minioTemplate;

    public static void fileToStream(String filePath, HttpServletResponse response) throws IframeException {
        InputStream inputStream = minioTemplate.downloadFile(filePath);
        fileToStream(inputStream, response);
    }
    public static void fileToStream(InputStream inputStream, HttpServletResponse response) {
        BufferedInputStream bufferedInputStream = null;
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            bufferedInputStream = new BufferedInputStream(inputStream);

            byte[] buffer = new byte[1024];
            int i = bufferedInputStream.read(buffer);
            while (i != -1) {
                outputStream.write(buffer, 0, i);
                i = bufferedInputStream.read(buffer);
            }
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
                if (bufferedInputStream != null) {
                    bufferedInputStream.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
    }

    public static void errorWrite(ErrorLoginEnum errorLoginEnum, HttpServletResponse response) {
        response.setContentType("application/json;charset=UTF-8");
        Result<String> result = Result.error(errorLoginEnum);
        PrintWriter printWriter = null;
        try {
            printWriter = response.getWriter();
            printWriter.println(JSON.toJSONString(result));
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            if (printWriter != null) {
                printWriter.close();
            }
        }
    }

    public static void importExcel(String fileName, String sheetName, HttpServletResponse response, Class baseEntity, List list) throws IframeException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        String encodedFilename = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replace(SYMBOL_PLUS, ENCODER_SYMBOL_PLUS);
        response.setHeader("Content-disposition", "attachment; filename=" + encodedFilename + ".xlsx");
        try {
            EasyExcel.write(response.getOutputStream()).head(baseEntity).excelType(ExcelTypeEnum.XLSX).sheet(sheetName).doWrite(list);
        } catch (IOException e) {
            log.error(e.getMessage());
            throw new IframeException("导出Excel失败");
        }

    }

    @Resource(name = "minioTemplate")
    public void setMinioTemplate(MinioTemplate minioTemplate) {
        IoUtils.minioTemplate = minioTemplate;
    }
}
